//
//  LoginViewController.m
//  Runone
//
//  Created by runone01 on 16/8/1.
//  Copyright © 2016年 runone. All rights reserved.
//


#import "LoginViewController.h"
#import "BCNetAPIClient.h"
#import "RunoneMainViewController.h"
#import "Token.h"
#import "MJExtension.h"
#import "AppLocalManager.h"
#import "AppSessionManager.h"
#import "Define.h"
#import "SVProgressHUD.h"
#import "CurrentEvent.h"
#import "RequestHelper.h"
#import "AppLocalManager.h"
#import "Define.h"
#import "CommonUtilityjudge.h"
#import "PromptUtil.h"
#import "UIView+Message.h"
#import "UITextField+ToolBar.h"
#import "UIView+Addition.h"
#import "PileInfo.h"
#import "AppDelegate.h"
#import "CommonUtility.h"
#import "SysUserInfo.h"
#import "SVProgressHUD.h"
#import "UIButton+touch.h"
#import "UIView+Addition.h"
#import "UIView+EKAlertView.h"

@interface LoginViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>
@property (weak, nonatomic) IBOutlet UITextField *userNameTF;
@property (weak, nonatomic) IBOutlet UITextField *passWordTF;
@property (weak, nonatomic) IBOutlet UIButton    *loginBtn;
@property (weak, nonatomic) IBOutlet UIButton    *rememberBtn;
@property (weak, nonatomic) IBOutlet UIImageView *backGroundImageV;

@property (nonatomic, assign) BOOL isLogin;
@property (nonatomic, assign) BOOL isRem;//是否记住密码
@property (nonatomic,   copy) NSString *i;

@property (nonatomic, strong) SysUserInfo *userInfo;
@property (nonatomic, strong) PromptUtil *Prompt;
@end

@implementation LoginViewController

#pragma    ------登录主界面

- (IBAction)rememberPassWordBtnClick:(UIButton *)sender {

    sender.selected=!sender.selected;
    if (sender.selected) {
        _isRem = YES; //
        _i     = @"1";
        [_rememberBtn setImage:[UIImage imageNamed:@"check_remember_password"] forState:UIControlStateNormal];
    } else {
        _i     = @"0";
        _isRem = NO;
        [_rememberBtn setImage:[UIImage imageNamed:@"remember_password"] forState:UIControlStateNormal];
    }
}
- (NSArray *)caculatePastOneYearWithADate:(NSString *)aDateStr {
    aDateStr = [NSString stringWithFormat:@"2017-04-20"];
    NSMutableArray *backArray = [[NSMutableArray alloc] init];
    NSString *yearStr = [aDateStr substringWithRange:NSMakeRange(0, 3)];
    NSString *monthStr = [aDateStr substringWithRange:NSMakeRange(4, 2)];
    NSString *dayStr  = [aDateStr substringWithRange:NSMakeRange(7, 2)];
    
    //今年今月到目前为止有几日
    NSMutableArray *tYTMDays = [[NSMutableArray alloc] init];
    for (int i = [dayStr intValue]; i > 0 ; i--) {
        NSString *iStr = [NSString stringWithFormat:@"%02d",i];
        [tYTMDays addObject:iStr];
    }
    //月份
    NSMutableArray *thisYMonthArray = [[NSMutableArray alloc] init];
    for (int i = [monthStr intValue]; i > 0; i ++) {
        NSString *iStr = [NSString stringWithFormat:@"%02d",i];
        [thisYMonthArray addObject:iStr];
    }
    //今年的每个月有多少天
    NSMutableArray *tYEMDays = [[NSMutableArray alloc] init];
    for (int i = [monthStr intValue]; i > 1; i-- ) {
        NSInteger monthEveryDays = [self DaysfromYear:([yearStr integerValue]) andMonth:i];
        NSString *iStr = [NSString stringWithFormat:@"%02ld",(long)monthEveryDays];
        for (int i = [iStr intValue]; i > 0; i --) {
            NSString *monthString = [NSString stringWithFormat:@"%02d",i];
            NSString *dayString   = [NSString stringWithFormat:@"%02ld",(long)monthEveryDays];
            NSString *tempYearString = [yearStr stringByAppendingString:@"年"];
            NSString *tempYearMonthString = [tempYearString stringByAppendingString:monthString];
            NSString *yearMonthString  = [tempYearMonthString stringByAppendingString:@"月"];
            NSString *tempYMDString = [yearMonthString stringByAppendingString:dayString];
            NSString *yMDString = [tempYMDString stringByAppendingString:@"日"];
            [tYEMDays addObject:yMDString];
        }
    }
    return backArray;
}

- (NSInteger)DaysfromYear:(NSInteger)year andMonth:(NSInteger)month {
    NSInteger num_year  = year;
    NSInteger num_month = month;
    
    BOOL isrunNian = num_year%4==0 ? (num_year%100==0? (num_year%400==0?YES:NO):YES):NO;
    switch (num_month) {
        case 1:case 3:case 5:case 7:case 8:case 10:case 12:{
            //[self setdayArray:31];
            return 31;
        }
        case 4:case 6:case 9:case 11:{
            //[self setdayArray:30];
            return 30;
        }
        case 2:{
            if (isrunNian) {
                //[self setdayArray:29];
                return 29;
            }else{
                // [self setdayArray:28];
                return 28;
            }
        }
        default:
            break;
    }
    return 0;
}


#pragma mark - 登录按钮点击
- (IBAction)loginBtnClick:(id)sender {
   
    
    if (stringIsEmpty(_userNameTF.text)) {
        [_Prompt alert:@"用户名不能为空"];
        return;
    }
    if (stringIsEmpty(_passWordTF.text)) {
        [_Prompt alert:@"密码不能为空"];
        return;
    }
    [self login];
}

//登录
- (void) login {
    [SVProgressHUD showWithStatus:@"正在加载中..."];
    NSDictionary *dic = [[NSDictionary alloc] init];
    dic=@{@"LoginName":_userNameTF.text,@"PassWord":_passWordTF.text,@"SystemCode":DefaultSystemCode ,@"grant_type":@"client_credentials",@"client_id":client_id,@"client_secret":client_secret};

    [[AppLocalManager sharedManager] DeleteDataByKey:ACCESS_TOKEN];
    [[BCNetAPIClient sharedJsonClient] requestJsonDataWithPath:GetLOGINURL withParams:dic withMethodType:1 andBlock:^(id data, NSError *error, AFHTTPRequestOperation *operation) {

        if (data) {
            if (_isRem == YES) {
                
                [[AppLocalManager sharedManager]saveData:_passWordTF.text andKey:@"RememberPassWord"];

                [[AppLocalManager sharedManager]saveData:_i andKey:@"R"];
            }
            else {
                [[AppLocalManager sharedManager]DeleteDataByKey: @"R"];
                [[AppLocalManager sharedManager]DeleteDataByKey:@"RememberUserName"];
                [[AppLocalManager sharedManager]DeleteDataByKey:@"RememberPassWord"];
            }
            [[AppLocalManager sharedManager]saveData:_userNameTF.text andKey:@"RememberUserName"];
//            [[AppLocalManager sharedManager] saveData:[NSNumber numberWithBool:self.isLogin] andKey:ISLOGIN];
            Token *token=[Token mj_objectWithKeyValues:data];
            [[AppLocalManager sharedManager] saveData:token.access_token andKey:ACCESS_TOKEN];
            [[AppLocalManager sharedManager] saveData:token.refresh_token andKey:REFRESH_TOKEN];
            [[BCNetAPIClient sharedJsonClient] refreshToken];
           
            [self requestUserBase];
            [SVProgressHUD showSuccessWithStatus:@"登录成功"];
        }
        if(error.code==-1001) {
//            [SVProgressHUD showSuccessWithStatus:@"网络超时，请稍后再试"];
            [SVProgressHUD dismiss];
            [UIView addEKNotifierWithText:@"网络超时，请稍后再试" dismissAutomatically:YES];
        }
        if(error.code == -1011) {
//            [SVProgressHUD showSuccessWithStatus:@"登录失败！"];
            [SVProgressHUD dismiss];
            [UIView addEKNotifierWithText:@"账号或密码错误" dismissAutomatically:YES];
        }
    }];
}

-(void)requestUserBase {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL=GetCurrentDutyPersonalName;
    getCurrentEventModel.DataValue = @"";
    getCurrentEventModel.UpdatedTime=@"";
    getCurrentEventModel.SystemCode=@"GuangleHighway";
    getCurrentEventModel.MethodName=@"GetUserInfo";
    
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        
        NSDictionary *dic = [requestOutginseng.DataValue mj_JSONObject];
        _userInfo         =  [SysUserInfo mj_objectWithKeyValues:dic];
        [[AppLocalManager sharedManager] saveData:_userInfo.UserUID  andKey:SYSUSERUID];
        [self requestSysRightGroupCode];
    };
    
    [requestHelper RequestGinsengModel:getCurrentEventModel andPushController:self];
}

- (void)requestSysRightGroupCode {
    RequestHelper *helper = [[RequestHelper alloc] init];
    
    RequestGinsengModel *GetSysRightGroup = [[RequestGinsengModel alloc] init];
    GetSysRightGroup.URL         = GetSysRightGroupCode;
    GetSysRightGroup.DataValue   = @"";
    GetSysRightGroup.UpdatedTime = @"";
    GetSysRightGroup.SystemCode  = @"GuangleHighway";
    GetSysRightGroup.MethodName  = @"GetSysRightGroupCode";
    
    helper.block = ^(RequestOutginseng *requestOutginseng, id dataValueModel) {
        if ([requestOutginseng.Code isEqualToString:@"001"]) {
            [[AppLocalManager sharedManager] saveData:requestOutginseng.DataValue  andKey:SYSRIGHTGROUPCODE];
            RunoneMainViewController *mainVC = [[RunoneMainViewController alloc] init];
            [self presentViewController:mainVC animated:YES completion:nil];
        } else {
            return;
        }
    };
    [helper RequestGinsengModel:GetSysRightGroup andPushController:self];
}


#pragma mark - life cycle
-(void)viewDidLoad {
    [super viewDidLoad];
    _Prompt  = [[PromptUtil alloc] init];
    _isRem = YES;
    _i     = @"1";
}
-(NSString *)jsonstr {
    NSArray *arr=@[@{@"key":@"VehicleNo",@"value":@"鄂N0881"},@{@"key":@"BegineTime",@"value":@"2017-04-06 14:30:00"},@{@"key":@"EndTime",@"value":@"2017-04-07 14:30:00"}];
    NSString *str=[arr mj_JSONString];
    return str;
}

- (void) viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    NSLog(@"账号密码%@---%@",GetRememberUserName,GetRememberPassWord);
    _userNameTF.text            = GetRememberUserName;
   // NSLog(@"%@ %@",GetRememberUserName, GetRememberPassWord);
    _passWordTF.secureTextEntry = YES;
    _passWordTF.text            = [[AppLocalManager sharedManager]getDataByKey:@"RememberPassWord"];
    _i = [NSString stringWithFormat:@"%@",[[AppLocalManager sharedManager]getDataByKey:@"R"]];
    if ([_i isEqualToString:@"1"]) {
        [_rememberBtn setImage:[UIImage imageNamed:@"check_remember_password"] forState:UIControlStateNormal];
        
                [[AppLocalManager sharedManager]saveData:_userNameTF.text andKey:@"RememberUserName"];
                [[AppLocalManager sharedManager]saveData:_passWordTF.text andKey:@"RememberPassWord"];
                [[AppLocalManager sharedManager]saveData:_i andKey:@"R"];
        
        [_rememberBtn setImage:[UIImage imageNamed:@"check_remember_password"] forState:UIControlStateNormal];
        _rememberBtn.selected = YES ;
        _isRem = YES;
    }
    else {
        [_rememberBtn setImage:[UIImage imageNamed:@"remember_password"] forState:UIControlStateNormal];
        _rememberBtn.selected = NO;
        _isRem = NO;
    }

    [self setUpLeftViewForTF:_userNameTF andImageStr:@"user_image"];
    [self setUpLeftViewForTF:_passWordTF andImageStr:@"login_lock_icon"];
}

- (void) setUpLeftViewForTF:(UITextField *)tf andImageStr:(NSString *)imageStr{
    UIImageView *imageV = [[UIImageView alloc] init];
    imageV.image    = [UIImage imageNamed:imageStr];
    tf.leftView     = imageV;
    tf.leftViewMode = UITextFieldViewModeAlways;
    [imageV sizeToFit];
}



@end
